import json

from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse
from django_redis import get_redis_connection
from apps.goods.models import SKU
from django.views import View
from utils.users import LoginRequiredJSONMixin

########################################购物车新增
class CartView(View):

    def post(self,request):
        #获取用户信息
        user = request.user
        # if user.is_authenticated:

        #接收参数
        data = json.loads(request.body.decode())
        #提取
        sku_id = data.get('sku_id')
        count = data.get('count')
        selectcd = data.get('selected')

        #验证
        if not all([sku_id,count]):
            return JsonResponse({'code':400,'errmsg':'参数不全'})

        try:
            sku = SKU.objects.get(id = sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有此商品'})
        try:
            count = int(count)
        except Exception:
            count = 1

        if selectcd:
            if not isinstance(selectcd,bool):
                return JsonResponse({'code':400,'errmsg':'参数错误'})


        #4,数据入库
        redis_cli = get_redis_connection('carts')

        #创建管道
        pipeline = redis_cli.pipeline()
        #     4.2 操作hash
        # HSET key field value
        pipeline.hset('carts_%s' %user.id,sku_id,count)
        #     4.3 操作set
        # 默认就是选中 (淘宝是默认不选中) 结合具体需求
        # SADD key member [member ...]
        pipeline.sadd('select_%s' %user.id,sku_id)

        #执行管道
        pipeline.execute()



        return JsonResponse({'code':0,'errmsg':'ok'})

#######################################购物车展示
    def get(self,request):
        redis_cli = get_redis_connection('carts')
        #{商品id ： count}获取所有商品
        sku_id_counts = redis_cli.hgetall('carts_%s'%request.user.id)

        #状态【商品id】
        selected_id = redis_cli.smembers('selected_%s'%request.user.id)

        #根据商品id查询商品
        data_list = []
        for sku_id,count in sku_id_counts.items(): #items() 所有键值对
            sku = SKU.objects.get(id = sku_id)
            #将对向转换为字典数据
            data_list.append({
                'id':sku.id,
                'count': int(count),  # 购物车数量
                'selected': sku_id in selected_id,  # 选中状态
                'amount': int(count) * int(sku.price),  # 商品金额小计
                'name': sku.name,
                'price': int(sku.price), # int( bytes) 将bytes类型转换为int类型
                'default_image_url': sku.default_image.url
            })

        # 3.返回响应
        return JsonResponse({
            "code": 0,
            "errmsg": "OK",
            "cart_skus": data_list
        })

    #################################购物车修改
    def put(self,request):
        user = request.user
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected')


        #查看SKU模型里id字段是否有sku_id (商品编号)
        try:
            sku = SKU.objects.get(id = sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有此商品'})

        #连接数据库
        redis_cli = get_redis_connection('carts')

        #更新hash     dist直接更新value值
        redis_cli.hset('carts_%s'%user.id,sku_id,count)

        #更新set
        if selected:
            redis_cli.sadd('selected_%s'%user.id,sku_id)
        else:
            # 未选中
            # 应该从集合中 移除
            '''
            SREM key member [member ...]

            移除集合 key 中的一个或多个 member 元素，不存在的 member 元素会被忽略'''

            redis_cli.srem('selected_%s'%user.id,sku_id)
            # 5. 返回响应  为了确保 前后端数据一致,我们要把后端的数据,再告诉前端
        cart_sku = {
            'id': sku_id,
            'name': sku.name,
            'count': count,
            'selected': selected,
            'price': sku.price,
            'amount': sku.price * int(count),
            'default_image_url': sku.default_image.url
        }
        return JsonResponse({'code': 0, 'cart_sku': cart_sku, 'errmsg': 'ok'})

    ###########################################购物车删除
    def delete(self,request):

        user = request.user
        data = json.loads(request.body.decode())

        sku_id = data.get('sku_id')

        try:
            sku = SKU.objects.get(id = sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'没有此商品'})

        #删除
        redis_cli = get_redis_connection('carts')
        redis_cli.hdel('carts_%s'%user.id,sku_id)
        redis_cli.srem('selected_%s'%user.id,sku_id)

        return JsonResponse({'code':0,'errmsg':'ok'})

#######################################全选购物车

class SelectallView(LoginRequiredJSONMixin,View):

    def put(self,request):

        user = request.user
        data = json.loads(request.body.decode())

        selected = data.get('selected',True)

        redis_cli = get_redis_connection('carts')

        skus = redis_cli.hgetall('carts_%s'%user.id) #{id:count}

        sku_list = skus.keys() #获取所有的key
        if selected:
            redis_cli.sadd('selected_%s'%user.id,*sku_list) #拆包

        else:
            redis_cli.srem('selected_%s'%user.id,*sku_list)

        return JsonResponse({'code':0,'errmsg':'ok'})

##################################################展示页面简单购物车

class CartsimpleView(LoginRequiredJSONMixin,View):

    def get(self,request):
        user = request.user

        redis_cli = get_redis_connection('carts')

        user_carts = redis_cli.hgetall('carts_%s'%user.id)#{id：count,id:count}
        selected = redis_cli.smembers('selected_%s'%user.id)#{id,id}

        cart_dict = {} #{id：{count：1，bool：ture}}

        for sku_id,count in user_carts.items():
            cart_dict[int(sku_id)] = {
                'count' : int(count),
                'selected':sku_id in selected
            }
        cart_skus = []
        sku_ids = cart_dict.keys() #（【id.id】）

        skus = SKU.objects.filter(id__in = sku_ids)#所有商品结果

        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'cart_skus': cart_skus})
